package com.isfto.controller;


import com.google.code.kaptcha.Producer;
import com.isfto.code.PageResult;
import com.isfto.code.ResponseData;
import com.isfto.entity.User;
import com.isfto.service.UserService;
import com.isfto.until.JwtUtils;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/sys/user")
public class UserController extends BaseController{

    @Autowired
    private UserService userService;

    @Autowired
    private Producer captchaProducer;

    @GetMapping("/captcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response) throws IOException {
        response.setContentType("image/jpeg");
        String captchaText = captchaProducer.createText();
        log.info("验证码为{}", captchaText);

        // Store the captcha text in the session
        session.setAttribute("captcha", captchaText);

        BufferedImage captchaImage = captchaProducer.createImage(captchaText);
        ImageIO.write(captchaImage, "jpg", response.getOutputStream());
    }

    /**
     * 用户登录
     */
    @GetMapping("/login")
    public ResponseData<Object> login(String username, String password, String captcha, HttpSession session) {
        String sessionCaptcha = (String) session.getAttribute("captcha");

        if (!sessionCaptcha.equals( captcha )){
            return returnObject( null );
        }
        User user = userService.login( username, password );
        if (user != null){
            Map<String, Object> claims = new HashMap<>();
            claims.put( "id",user.getId() );
            claims.put( "username",user.getUsername() );
            String jwt = JwtUtils.generateJwt( claims );
            ResponseData<Object> responseData = new ResponseData<>();
            responseData.setErrorCode( String.valueOf( 200 ) );
            responseData.setMsg( user.getRole() );
            responseData.setData( jwt );
            return responseData;
        }else {
            return returnObject( null );
        }

    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @PostMapping("/add")
    public ResponseData<Boolean> add(@RequestBody User user){
        log.info( "用户注册 {}",user );
        Boolean adduser = userService.adduser( user );
        return returnBoolean( adduser );
    }

    /**
     * 分页查询用户
     */
    @GetMapping("/gets")
    public  ResponseData<Object> getUsers( @RequestParam(defaultValue = "1") int page,
                                           @RequestParam(defaultValue = "10") int pageSize){
        PageResult users = userService.getUsers( page, pageSize );
        return returnObject( users );
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/del/{id}")
    public ResponseData<Boolean> delUserById(@PathVariable Integer id){
        return returnBoolean( userService.delById(id) ) ;
    }


}
